import os.path
import re

import parsel
import requests
#导入漂亮表格的模块
import prettytable as pt

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'
}

def search(keyword):
    search_url = f'http://www.1biqug.net/searchbook.php?keyword={keyword}'
    #发送请求
    search_data = requests.get(search_url)
    #解析数据，提取小说名字，作者，小说id
    selector = parsel.Selector(search_data.text)
    lis = selector.css('.novelslist2 li')
    #将小说信息保存到字典中
    novel_info = []
    #生成表格
    tb = pt.PrettyTable()
    tb.field_names = ['序号','书名','作者','书ID']
    num = 0
    for li in lis[1:]:
        name = li.css('.s2 a::text').get()
        novel_id = li.css('.s2 a::attr(href)').get().replace('/','')
        writer = li.css('.s4::text').get()
        dit = {
            'name':name,
            'writer':writer,
            'novel_id':novel_id
        }
        tb.add_row([num,name,writer,novel_id])
        num += 1
        novel_info.append(dit)
    print('你搜索的结果如下：')
    print(tb)
    nuvel_num = input('请输入你想要下载的小说需要：')
    novel_id = novel_info[int(nuvel_num)]['novel_id']
    print(novel_id[4:])
    return novel_id[4:]


def get_title_author(html_url):
    response =  requests.get(url=html_url,headers=headers)
    response.encoding = response.apparent_encoding #解决乱码问题
    select = parsel.Selector(response.text)
    title = select.css('#info h1::text').get()
    author = select.css('#info a::text').get()
    return title,author

def get_reponse(html_url):
    response =  requests.get(url=html_url,headers=headers)
    response.encoding = response.apparent_encoding #解决乱码问题
    print(response.text)
    return  response.text

def get_list(html_url):
    response =  requests.get(url=html_url,headers=headers)
    response.encoding = response.apparent_encoding #解决乱码问题
    #获取所有章节
    list = re.findall('<a style="" href="(.*?)">',response.text)
    return  list

def get_content(html_url):
    """
    获取章节名字和内容
    :param html_url: 章节url
    :return:
    """
    response =  requests.get(url=html_url,headers=headers)
    response.encoding = response.apparent_encoding #解决乱码问题
    selector = parsel.Selector(response.text)
    #章节名字
    name = selector.css('.bookname h1::text').get()
    #章节内容
    content =  selector.css('#content::text').getall()
    content_result = '\n'.join(content)
    return name,content_result

def save(name,title,content):
  """

  :param name: 小说名字
  :param title: 章节名字
  :param content: 内容
  :return:
  """
  file = f'{name}\\'
  if not os.path.exists(file):
         os.mkdir(file)
  with open(file+name+'.txt',mode='a',encoding='utf-8') as f:
      f.write(title)
      f.write('\n')
      f.write(content)
      f.write('\n')
  print(title,'已保存')




if __name__ == '__main__':
    # keyword = input("请输入小说名")
    # book_id = search(keyword)
    book_id = 13511
    html_url = f'http://www.1biqug.net/book/{book_id}/'
    #小说名字，作者
    title,author = get_title_author(html_url)
    print(title,author)
    #获取所有章节
    list_url = get_list(html_url)
    for i in list_url:
        url = f'http://www.1biqug.net/book/{book_id}/'+ i[11:]
        #章节名字，内容
        name,content_result = get_content(url)
        break







